package com.imooc.chart.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class YouTubeBgmDownloader {
    public static void main(String[] args) {
        String videoUrl = "https://www.youtube.com/watch?v=bXKJEBaz-Vw"; // 替换为实际的 YouTube 视频链接
        String outputDirectory = "/Users/dengwubo/Music/tts/bgm"; // 替换为实际的输出目录

        try {
            downloadAudio(videoUrl, outputDirectory);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void downloadAudio(String videoUrl, String outputDirectory) throws IOException, InterruptedException {
        // 设置代理环境变量（如果需要）
        setProxy();

        // 构建下载命令
        String downloadCommand = String.format("/Users/dengwubo/Movies/sucai/yt-dlp_macos --extract-audio --audio-format m4a -o \"%s/%%(title)s.%%(ext)s\" \"%s\"", outputDirectory, videoUrl);

        // 执行命令
        ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", downloadCommand);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        // 读取命令输出
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }

        // 等待命令执行完成
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            System.err.println("Download failed with exit code: " + exitCode);
        } else {
            System.out.println("Download successful for: " + videoUrl);
        }
    }

    private static void setProxy() {
        // 设置代理环境变量（如果需要）
        System.setProperty("https.proxyHost", "127.0.0.1");
        System.setProperty("https.proxyPort", "7890");
        System.setProperty("http.proxyHost", "127.0.0.1");
        System.setProperty("http.proxyPort", "7890");
        System.setProperty("all.proxyHost", "127.0.0.1");
        System.setProperty("all.proxyPort", "7890");
    }
}
